import { Drawer, Form, Input, Button, message } from 'antd'
import { useImperativeHandle, useState, forwardRef } from 'react'
import { updatepassword } from '@/api/user'
import { removeToken } from '@/utils/auth'
import { useNavigate } from 'react-router-dom'
import { LockOutlined } from '@ant-design/icons'

// 定义子组件暴露的方法类型
interface ChildHandle {
  showDrawer: () => void
}
function EditPwd(props: any, ref: React.Ref<ChildHandle>) {
  console.log(props)
  const [open, setOpen] = useState(false)
  useImperativeHandle(ref, () => {
    return { showDrawer }
  })
  const [form] = Form.useForm()
  const nav = useNavigate()
  const showDrawer = () => {
    setOpen(true)
  }

  const onClose = () => {
    form.resetFields()

    setOpen(false)
  }
  const editSave = () => {
    form
      .validateFields()
      .then(values => {
        updatepassword(values).then(res => {
          if (res.status === 200) {
            message.success('修改成功')
            removeToken()
            onClose()
            nav('/login')
          }
        })
      })
      .catch(err => {
        console.log(err)
      })
  }
  const btn = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={editSave}>
        确认
      </Button>
      <Button size='large' style={{ marginLeft: '15px' }} onClick={onClose}>
        取消
      </Button>
    </div>
  )
  return (
    <>
      <Drawer title='修改密码' onClose={onClose} open={open} footer={btn}>
        <Form form={form} name='dependencies' autoComplete='off' style={{ maxWidth: 600 }} layout='vertical'>
          <Form.Item label='原始密码' name='oldpassword' rules={[{ required: true, message: '请输入原始密码' }]}>
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>
          <Form.Item label='新密码' name='password' rules={[{ required: true, message: '请输入新密码' }]}>
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>

          {/* Field */}
          <Form.Item
            label='确认密码            '
            name='repassword'
            dependencies={['password']}
            rules={[
              {
                required: true,
                message: '请再次输入新密码'
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不正确'))
                }
              })
            ]}
          >
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}
export default forwardRef(EditPwd)
